package com.lty.jeeg.server.modules.sys.service.impl;

import java.util.List;
import java.util.UUID;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.lty.jeeg.server.common.constant.UserConstants;
import com.lty.jeeg.server.common.vo.UserVO;
import com.lty.jeeg.server.modules.sys.dao.RoleDao;
import com.lty.jeeg.server.modules.sys.dao.UserDao;
import com.lty.jeeg.server.common.dto.UserDto;
import com.lty.jeeg.server.modules.sys.model.Role;
import com.lty.jeeg.server.modules.sys.model.User;
import com.lty.jeeg.server.modules.sys.service.UserService;
import com.lty.jeeg.server.common.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

/**
 * @author LTY
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;
	@Autowired
	private RoleDao roleDao;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public User saveUser(UserDto userDto) {
		userDto.setSalt(DigestUtils
				.md5Hex(UUID.randomUUID().toString() + System.currentTimeMillis() + UUID.randomUUID().toString()));
		userDto.setPassword(passwordEncoder(userDto.getPassword(), userDto.getSalt()));
		userDto.setStatus(User.Status.VALID.getCode());
		userDto.preInsert();
		userDao.save(userDto);
		saveUserRoles(userDto.getId(), userDto.getRoleIds());

		log.debug("新增用户{}", userDto.getUsername());
		return userDto;
	}

	private void saveUserRoles(Long userId, List<Long> roleIds) {
		if (roleIds != null) {
			userDao.deleteUserRole(userId);
			if (!CollectionUtils.isEmpty(roleIds)) {
				userDao.saveUserRoles(userId, roleIds);
			}
		}
	}

	@Override
	public String passwordEncoder(String credentials, String salt) {
		Object object = new SimpleHash("MD5", credentials, salt, UserConstants.HASH_ITERATIONS);
		return object.toString();
	}

	@Override
	public User getUser(String username) {
		return userDao.getUser(username);
	}

	@Override
	public void changePassword(String username, String oldPassword, String newPassword) {
		User u = userDao.getUser(username);
		if (u == null) {
			throw new IllegalArgumentException("用户不存在");
		}

		if (!u.getPassword().equals(passwordEncoder(oldPassword, u.getSalt()))) {
			throw new IllegalArgumentException("密码错误");
		}

		userDao.changePassword(u.getId(), passwordEncoder(newPassword, u.getSalt()));

		log.debug("修改{}的密码", username);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public User updateUser(UserDto userDto) {
		if (!StringUtils.isEmpty(userDto.getPassword())) {
			userDto.setSalt(userDao.getById(userDto.getId()).getSalt());
			userDto.setPassword(passwordEncoder(userDto.getPassword(), userDto.getSalt()));
		}
		userDto.preUpdate();
		userDao.update(userDto);
		saveUserRoles(userDto.getId(), userDto.getRoleIds());
		updateUserSession(userDto.getId());
		return userDto;
	}

	private void updateUserSession(Long id) {
		User current = UserUtil.getCurrentUser();
		if (current.getId().equals(id)) {
			User user = userDao.getById(id);
			UserUtil.setUserSession(user);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delete(Long id) {
		userDao.delete(id);
		userDao.deleteUserRole(id);
	}

    @Override
    public JSONArray listAll() {
		List<UserVO> userDtoList = userDao.listAll();
        return JSONArray.parseArray(JSON.toJSONString(userDtoList));
    }

	@Override
	public JSONArray partList(Long id) {
		List<UserVO> userDtoList = userDao.partList(id);
		return JSONArray.parseArray(JSON.toJSONString(userDtoList));
	}


	@Override
	public User currentUser() {
		User loginUser = UserUtil.getCurrentUser();
		List<Role> roles = roleDao.listByUserId(loginUser.getId());
		loginUser.setRoleList(roles);
		return loginUser;
	}

}
